<template>
  <div class="account-info">
    <h2>账号信息</h2>
    <el-button type="primary" @click="openEditDialog" size="mini">修改用户信息</el-button>
    <el-button type="primary" @click="openChangePasswordDialog" size="mini">修改密码</el-button>
    <el-card shadow="always" style="margin-bottom: 10px;" v-if="userInfo">
      <el-row :gutter="20">
        <el-col :span="12">
          <p><strong>用户ID：</strong> {{ userInfo.id }} </p>
        </el-col>
        <el-col :span="12">
          <p><strong>性别：</strong> {{ userInfo.sex === 1 ? '男' : '女' }} </p>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <p><strong>登录名：</strong> {{ userInfo.loginName }} </p>
        </el-col>
        <el-col :span="12">
          <p><strong>用户名：</strong> {{ userInfo.userName }} </p>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <p><strong>电话号码：</strong> {{ userInfo.mobile }} </p>
        </el-col>
        <el-col :span="12">
          <p><strong>邮箱：</strong> {{ userInfo.email }} </p>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <p><strong>身份证号：</strong> {{ userInfo.identityCode }} </p>
        </el-col>
        <el-col :span="12">
          <p><strong>创建时间：</strong> {{ userInfo.createTime }} </p>
        </el-col>
      </el-row>
    </el-card>
    
    <!-- 编辑用户信息对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="showEditDialog" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editForm" label-width="80px">
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="editForm.loginName"></el-input>
        </el-form-item>

        <el-form-item label="用户名" prop="userName">
          <el-input v-model="editForm.userName"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="editForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>

        <el-form-item label="身份证号" prop="identityCode">
          <el-input v-model="editForm.identityCode"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 修改密码对话框 -->
    <el-dialog title="修改密码" :visible.sync="showChangePasswordDialog" width="500px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password"></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="showChangePasswordDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitPasswordForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue';
import {Col, Row, Card} from 'element-ui';
Vue.use(Col);
Vue.use(Row);
Vue.use(Card);
export default {
  
  data() {
    return {
      userId: null,
      userInfo: null,
      showEditDialog: false,
      showChangePasswordDialog: false,
      editForm: {
        id: '',
        loginName: '',
        userName: '',
        sex: '',
        mobile: '',
        email: '',
        identityCode: '',
      },
      passwordForm: {
        id: '',
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      editRules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        identityCode: [{ required: true, message: '请输入身份证号', trigger: 'blur' },
          { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号格式', trigger: 'blur' }
        ]
      },
      passwordRules: {
        oldPassword: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 10, message: '密码长度为6-10位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    getUserId() {
      // 使用与 getUserList 相同的请求方式
      this.$axios({
        url: "/api/user/getUserId", // 确保使用正确的URL
        method: "POST",
        params: {  // 使用 params 传递 token
          token: sessionStorage.getItem("token")
        }
      })
      .then(res => {
        console.log('getUserId response:', res); // 添加日志查看响应
        if (res.data.code == 5200) {
          this.userId = res.data.userId;
          this.getUserInfo();
        } else {
          console.error('获取userID失败:', res);
        }
      })
      .catch(error => {
        console.error('Error fetching user ID:', error.response || error);
      });
    },
  
    getUserInfo() {
      this.$axios({
        url: "/api/user/detail",
        method: "POST",
        data: {
          userId: this.userId
        }
      })
      .then(res => {
        console.log('getUserInfo response:', res); // 添加日志查看响应
        if (res.data.code == 5200) {
          this.userInfo = res.data.userInfo;
          console.log('userInfo:----------', this.userInfo);
        } else {
          console.error('Failed to get user info:', res);
        }
      })
      .catch(error => {
        console.error('Error fetching user info:', error.response || error);
      });
    },

    openEditDialog() {
      // 初始化 editForm（从 userInfo 填充）
      this.editForm = {
        id: this.userInfo.id,
        loginName: this.userInfo.loginName,
        userName: this.userInfo.userName,
        sex: this.userInfo.sex,
        mobile: this.userInfo.mobile,
        email: this.userInfo.email,
        identityCode: this.userInfo.identityCode
      };
      this.showEditDialog = true;
    },

    openChangePasswordDialog() {
      // 初始化 passwordForm
      this.passwordForm = {
        id: this.userInfo.id,
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      this.showChangePasswordDialog = true;
    },

    submitEditForm() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          // 发送请求更新用户信息
          this.$axios({
            url: "/api/user/modifyuser",
            method: "post",
            data: {
              id: this.editForm.id,
              loginName: this.editForm.loginName,
              userName: this.editForm.userName,
              sex: this.editForm.sex,
              mobile: this.editForm.mobile,
              email: this.editForm.email,
              identityCode: this.editForm.identityCode
            }
          })
          .then(res => {
            if (res.data.code === 5200) {
              this.$message.success('修改成功！');
              this.showEditDialog = false;
              // 刷新用户信息
              this.getUserInfo();
            } else {
              this.$message.error('修改失败：' + res.data.msg);
            }
          })
          .catch(() => {
            this.$message.error('提交失败');
          });
        } else {
          this.$message.warning('请填写完整且正确的信息');
        }
      });
    },
    
    submitPasswordForm() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          // 发送请求更新密码
          this.$axios({
            url: "/api/user/modifyuser",
            method: "post",
            data: {
              id: this.passwordForm.id,
              oldPassword: this.passwordForm.oldPassword,
              newPassword: this.passwordForm.newPassword
            }
          })
          .then(res => {
            if (res.data.code === 5200) {
              this.$message.success('密码修改成功！');
              this.showChangePasswordDialog = false;
            } else {
              this.$message.error('密码修改失败：' + res.data.msg);
            }
          })
          .catch(() => {
            this.$message.error('提交失败');
          });
        } else {
          this.$message.warning('请填写完整且正确的信息');
        }
      });
    }
  },

  mounted() {
    this.getUserId();
  }
};
</script>

<style scoped>
.account-info {
  padding: 20px;
  width: 70%;
  float: right;
  margin-right: 5rem;
}

h2 {
  padding: 10px;
}

.el-card {
  background-color: #f5f7fa;
  margin: 20px 0px;
}

.el-row {
  margin: 20px 0px;
}

.el-col p {
  font-size: 14px;
  color: #606266;
}

.el-col strong {
  font-weight: bold;
}
</style>